<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>俄罗斯方块</title>
  <style>
    body {
      background: #1a1a1a;
      display: flex;
      justify-content: center;
      font-family: Arial;
    }
    #game-container {
      position: relative;
      margin-top: 2rem;
    }
    #game-board {
      border: 2px solid #333;
      background: #000;
    }
    .info-panel {
      color: white;
      position: absolute;
      left: 320px;
      top: 0;
      padding: 1rem;
    }
    .controls {
      margin-top: 1rem;
    }
  </style>
</head>
<body>
  <div id="game-container">
    <canvas id="game-board" width="300" height="600"></canvas>
    <div class="info-panel">
      <div>得分: <span id="score">0</span></div>
      <div>最高分: <span id="high-score">0</span></div>
      <button class="controls" id="start-btn">开始游戏</button>
    </div>
  </div>
<script>
// 游戏配置
const COLS = 10, ROWS = 20;
const BLOCK_SIZE = 30;
const SHAPES = [  // 所有方块形状
  [[1,1,1,1]],               // I
  [[1,1,1], [0,1,0]],        // T
  [[1,1,1], [1,0,0]],        // L
  [[1,1,1], [0,0,1]],        // J
  [[1,1], [1,1]],            // O
  [[1,1,0], [0,1,1]],        // S
  [[0,1,1], [1,1,0]]         // Z
];
class Tetris {
  constructor() {
    this.canvas = document.getElementById('game-board');
    this.ctx = this.canvas.getContext('2d');
    this.board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
    this.score = 0;
    this.highScore = localStorage.getItem('tetrisHighScore') || 0;
    this.currentPiece = null;
    this.gameLoop = null;
    // 初始化事件
    document.addEventListener('keydown', this.handleKey.bind(this));
    document.getElementById('start-btn').addEventListener('click', () => this.start());
  }
  // 生成新方块
  spawnNewPiece() {
    const shape = SHAPES[Math.floor(Math.random() * SHAPES.length)];
    this.currentPiece = {
      shape,
      x: Math.floor(COLS/2) - Math.floor(shape[0].length/2),
      y: 0
    };
  }
  // 碰撞检测
  checkCollision() {
    const { shape, x, y } = this.currentPiece;
    return shape.some((row, i) => 
      row.some((cell, j) => {
        if (!cell) return false;
        const newX = x + j;
        const newY = y + i;
        return newX < 0 || newX >= COLS || newY >= ROWS || 
               (newY >= 0 && this.board[newY][newX]);
      })
    );
  }
  // 方块旋转
  rotate() {
    const rotated = this.currentPiece.shape[0].map((_, i) =>
      this.currentPiece.shape.map(row => row[i]).reverse()
    );
    const previousShape = this.currentPiece.shape;
    this.currentPiece.shape = rotated;
    if (this.checkCollision()) {
      this.currentPiece.shape = previousShape;  // 回退旋转
    }
  }
  // 合并到棋盘
  merge() {
    const { shape, x, y } = this.currentPiece;
    shape.forEach((row, i) => {
      row.forEach((cell, j) => {
        if (cell && y + i >= 0) {
          this.board[y + i][x + j] = 1;
        }
      });
    });
  }
  // 消除满行
  clearLines() {
    let linesCleared = 0;
    for (let y = ROWS - 1; y >= 0; y--) {
      if (this.board[y].every(cell => cell)) {
        this.board.splice(y, 1);
        this.board.unshift(Array(COLS).fill(0));
        linesCleared++;
        y++; // 重新检查当前行
      }
    }
    if (linesCleared) {
      this.score += linesCleared * 100;
      document.getElementById('score').textContent = this.score;
    }
  }
  // 游戏循环
  update() {
    this.currentPiece.y++;
    if (this.checkCollision()) {
      this.currentPiece.y--;
      this.merge();
      this.clearLines();
      this.spawnNewPiece();
      if (this.checkCollision()) {
        this.gameOver();
      }
    }
    this.draw();
  }
  // 绘制游戏
  draw() {
    this.ctx.fillStyle = '#000';
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    // 绘制棋盘
    this.board.forEach((row, y) => {
      row.forEach((cell, x) => {
        if (cell) {
          this.ctx.fillStyle = '#f00';
          this.ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, 
                           BLOCK_SIZE - 1, BLOCK_SIZE - 1);
        }
      });
    });
    // 绘制当前方块
    if (this.currentPiece) {
      this.ctx.fillStyle = '#0f0';
      this.currentPiece.shape.forEach((row, y) => {
        row.forEach((cell, x) => {
          if (cell) {
            this.ctx.fillRect(
              (this.currentPiece.x + x) * BLOCK_SIZE,
              (this.currentPiece.y + y) * BLOCK_SIZE,
              BLOCK_SIZE - 1,
              BLOCK_SIZE - 1
            );
          }
        });
      });
    }
  }
  // 游戏结束
  gameOver() {
    clearInterval(this.gameLoop);
    alert(`游戏结束！得分: ${this.score}`);
    if (this.score > this.highScore) {
      localStorage.setItem('tetrisHighScore', this.score);
    }
    this.reset();
  }
  // 重置游戏
  reset() {
    this.board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
    this.score = 0;
    document.getElementById('score').textContent = 0;
  }
  // 开始游戏
  start() {
    this.reset();
    this.spawnNewPiece();
    this.gameLoop = setInterval(() => this.update(), 1000);
  }
  // 键盘控制
  handleKey(e) {
    if (!this.currentPiece) return;
    switch(e.key) {
      case 'ArrowLeft':
        this.currentPiece.x--;
        if (this.checkCollision()) this.currentPiece.x++;
        break;
      case 'ArrowRight':
        this.currentPiece.x++;
        if (this.checkCollision()) this.currentPiece.x--;
        break;
      case 'ArrowDown':
        this.currentPiece.y++;
        if (this.checkCollision()) this.currentPiece.y--;
        break;
      case 'ArrowUp':
        this.rotate();
        break;
    }
    this.draw();
  }
}
// 启动游戏
new Tetris();
</script>
</body>
</html>
